﻿<%@ WebHandler Language="C#" Class="Event" %>

using System;
using System.Web;
using LdExpress;
using Newtonsoft.Json;
using System.Data;
using System.Collections;

public class Event : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";

        var action = context.Request.Params["action"];
        if (!string.IsNullOrEmpty(action))
        {
            switch (action.ToLower())
            {
                case "d":
                    DeleteEvent(context);
                    break;
                case "archived":
                    ArchivedEvent(context);
                    break;

                case "notified":
                    UpdateEvent(context);
                    break;
                case "notify":
                    GetEventForNotify(context);
                    break;
                case "timeunit":
                    GetEventTimeUnit(context);
                    break;
                case "updatestatus":
                    DoUpdateEventArchive(context);
                    break;
                case "listregionschedule":
                    GetListRegionSchedules(context);
                    break;
                case "listcountry":
                    GetListCountryFromPorts(context);
                    break;
                case "deletegpnotice":
                    DoDeleteGPNotice(context);
                    break;
                case "listcustomer":
                    GetListCustomer(context);
                    break;
                case "listcarrier":
                    GetListCarrier(context);
                    break;
                case "listusername":
                    GetListUserName(context);
                    break;
                case "listservicearea":
                    GetListServiceArea(context);
                    break;
                case "listserviceareacode":
                    GetListServiceAreaCode(context);
                    break;

            }
        }
    }

    private void DeleteEvent(HttpContext context)
    {
        var _id = context.Request.Params["id"];
        long id = 0;
        var result = "ok";
        if (long.TryParse(_id, out id) && id > 0)
        {
            EventInfo obj = new EventInfo();
            obj.ID = id;
            obj.Load(GV.cn, GV.trans);
            //update trang thai            
            obj.Delete(GV.cn, GV.trans);
        }
        else
        {
            result = "notok";
        }

        JsonConvert.SerializeObject("ok");
        context.Response.Write(result);
    }
    private void ArchivedEvent(HttpContext context)
    {
        var _id = context.Request.Params["id"];
        long id = 0;
        var result = "ok";
        if (long.TryParse(_id, out id) && id > 0)
        {
            EventInfo obj = new EventInfo();
            obj.ID = id;
            obj.Load(GV.cn, GV.trans);
            //update trang thai
            obj.Status = -1;
            obj.LastUpdatedDate = DateTime.Now;
            obj.Save(GV.cn, GV.trans);
        }
        else
        {
            result = "notok";
        }

        JsonConvert.SerializeObject("ok");
        context.Response.Write(result);
    }
    private void UpdateEvent(HttpContext context)
    {
        var _id = context.Request.Params["id"];
        long id = 0;
        var result = "ok";
        if (long.TryParse(_id, out id) && id > 0)
        {
            EventInfo obj = new EventInfo();
            obj.ID = id;
            obj.Load(GV.cn, GV.trans);
            //update trang thai
            obj.Status = 0;
            obj.LastUpdatedDate = DateTime.Now;
            obj.Save(GV.cn, GV.trans);
        }
        else
        {
            result = "notok";
        }

        JsonConvert.SerializeObject("ok");
        context.Response.Write(result);
    }

    public void GetEventForNotify(HttpContext context)
    {
        DataSet ds = null;
        int nNumOfPages = 0;
        int NumOfItemsPerPage = 999;
        int PageNo = 1;
        DateTime now = DateTime.Now;
        string condition = " and Status=1 and EndDate >'" + now.ToString("yyyy-MM-dd HH:mm:ss") + "'";
        EventInfo obj = new EventInfo();
        obj.GetList(condition, "", "", "StartDate desc", NumOfItemsPerPage, PageNo, out nNumOfPages, out ds, GV.cn, GV.trans);

        if (ds != null && ds.Tables != null)
        {
            ArrayList source = new ArrayList();

            object dynamic;
            int index = 0;
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                dynamic = new
                {
                    ID = row["ID"].ToString(),
                    Name = row["Name"].ToString(),
                    Description = row["Description"].ToString(),
                    StartDate = row["StartDate"].ToString(),
                    Color = row["ColorEV"] == null ? "" : row["ColorEV"].ToString(),
                    EventType = row["EventType"].ToString(),
                    Remaining = GetRemainingTime(now, Convert.ToDateTime(row["StartDate"].ToString()), Convert.ToInt16(row["AlarmTime"].ToString()), Convert.ToInt16(row["AlarmType"].ToString()))
                };

                source.Add(dynamic);
            }

            var str = JsonConvert.SerializeObject(source);
            context.Response.Write(str);

        }
        else
        {
            context.Response.Write(JsonConvert.SerializeObject("empty"));
        }
    }
    public void DoUpdateEventArchive(HttpContext context)
    {
        DataSet ds = null;
        int nNumOfPages = 0;
        int NumOfItemsPerPage = 999;
        int PageNo = 1;
        DateTime now = DateTime.Now;
        string condition = " and Status=0 and LastUpdatedDate < '" + now.ToString("yyyy-MM-dd 00:00:00") + "'";
        EventInfo obj = new EventInfo();
        obj.GetList(condition, "", "", "StartDate desc", NumOfItemsPerPage, PageNo, out nNumOfPages, out ds, GV.cn, GV.trans);
        foreach (DataRow row in ds.Tables[0].Rows)
        {
            string strSQL = " update tbl_eventinfo set status=-1 where id=" + row["ID"].ToString(); ;
            DBModule.ExecuteNonQuery(strSQL, GV.cn, GV.trans);
        }
    }
    public double GetRemainingTime(DateTime from, DateTime to, int alarmtime, int alarmtype)
    {
        if (to < from)
            return -1;

        double before = 5;//millisecon
        if (alarmtype == 1)
        {
            before = alarmtime * 60 * 1000;
        }
        else if (alarmtype == 2)
        {
            before = alarmtime * 60 * 60 * 1000;
        }

        TimeSpan span = to - from;

        if (span.TotalMilliseconds > before)
        {
            return span.TotalMilliseconds - before;
        }
        else
        {
            return 5000;
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    public void GetEventTimeUnit(HttpContext context)
    {
        DataSet ds = null;
        int nNumOfPages = 0;
        int NumOfItemsPerPage = 999;
        int PageNo = 1;
        DateTime now = DateTime.Now;
        string condition = " and Status >= 0 and userid=" + context.Session["logined_id"];

        EventInfo obj = new EventInfo();
        obj.GetList(condition, "", "", "StartDate desc", NumOfItemsPerPage, PageNo, out nNumOfPages, out ds, GV.cn, GV.trans);

        if (ds != null && ds.Tables != null)
        {

            ArrayList source = new ArrayList();

            object dynamic;
            bool isExit;
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                isExit = false;
                switch (row["TimeUnit"].ToString())
                {
                    case "1":
                    case "2":
                    case "3":
                    case "4":
                        isExit = CheckHours(row["TimeUnit"].ToString());
                        break;
                    case "5":
                    case "6":
                    case "7":
                        isExit = CheckWeek(row["TimeUnit"].ToString());
                        break;
                    case "8":
                    case "9":
                    case "10":
                        isExit = CheckDay(row["TimeUnit"].ToString());
                        break;
                    case "11":
                    case "12":
                    case "13":
                        isExit = CheckMonth(row["TimeUnit"].ToString());
                        break;
                }
                if (isExit)
                {

                    dynamic = new
                    {
                        ID = row["ID"].ToString(),
                        Name = row["Name"].ToString(),
                        Description = row["Description"].ToString(),
                        StartDate = row["StartDate"].ToString(),
                        Color = row["ColorEV"] == null ? "" : row["ColorEV"].ToString(),
                        EventType = row["EventType"].ToString(),
                        TimeUnit = isExit,
                        Remaining = GetRemainingTime(now, Convert.ToDateTime(row["StartDate"].ToString()), Convert.ToInt16(row["AlarmTime"].ToString()), Convert.ToInt16(row["AlarmType"].ToString()))
                    };
                    source.Add(dynamic);
                }
            }

            var str = JsonConvert.SerializeObject(source);
            context.Response.Write(str);
        }
        else
        {
            context.Response.Write(JsonConvert.SerializeObject("empty"));
        }
    }
    public bool CheckHours(string timeUnit)
    {
        bool isExit = false;
        int timeHours = DateTime.Now.Hour;
        if (timeUnit == "1" && (timeHours >= 8 && timeHours < 10))
            isExit = true;
        if (timeUnit == "2" && (timeHours >= 11 && timeHours < 13))
            isExit = true;
        if (timeUnit == "3" && (timeHours >= 13 && timeHours < 15))
            isExit = true;
        if (timeUnit == "4" && (timeHours >= 16 && timeHours < 18))
            isExit = true;

        return isExit;
    }
    public bool CheckWeek(string timeUnit)
    {
        bool isExit = false;
        DateTime d = DateTime.Now;

        int dayofweek = (int)DateTime.Now.DayOfWeek;
        if (timeUnit == "5" && (dayofweek <= 2))
            isExit = true;
        if (timeUnit == "6" && (dayofweek == 3))
            isExit = true;
        if (timeUnit == "7" && (dayofweek >= 4 && dayofweek <= 5))
            isExit = true;
        return isExit;
    }
    public bool CheckDay(string timeUnit)
    {
        bool isExit = false;

        int day = (int)DateTime.Now.Day;

        if (timeUnit == "8" && (day >= 1 && day <= 5))
            isExit = true;
        if (timeUnit == "9" && (day >= 13 && day <= 18))
            isExit = true;
        if (timeUnit == "10" && (day >= 25 && day <= 31))
            isExit = true;
        return isExit;
    }
    public bool CheckMonth(string timeUnit)
    {
        bool isExit = false;
        int month = (int)DateTime.Now.Month;
        if (timeUnit == "11" && (month >= 1 && month <= 3))
            isExit = true;
        if (timeUnit == "12" && (month >= 5 && month <= 7))
            isExit = true;
        if (timeUnit == "13" && (month >= 10 && month <= 12))
            isExit = true;
        return isExit;
    }
    public void GetListRegionSchedules(HttpContext context)
    {
        DataSet ds = null;
        string sql = "";
        sql = "SELECT DISTINCT Region FROM tbl_ports ORDER BY Region";
        ds = DBModule.ExecuteQuery(sql, GV.cn, GV.trans);

        if (ds != null && ds.Tables != null)
        {
            ArrayList source = new ArrayList();
            string arrRegion = null;
            object dynamic;
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                source.Add(row["Region"].ToString());
                //if (arrRegion.Length > 0)
                //    arrRegion += ",\"" + row["Region"].ToString() + "\"";
                //else
                //    arrRegion += "\"" + row["Region"].ToString() + "\"";
                //dynamic = new
                //{
                //    Region = row["Region"].ToString()
                //};
                //source.Add(dynamic);
            }
            var str = JsonConvert.SerializeObject(source);
            context.Response.Cache.SetExpires(DateTime.Now.AddSeconds(600));
            context.Response.Cache.SetCacheability(HttpCacheability.Public);
            context.Response.Write(str);
        }
        else
        {
            context.Response.Write(JsonConvert.SerializeObject("empty"));
        }
    }
    public void GetListCountryFromPorts(HttpContext context)
    {
        DataSet ds = null;
        string sql = "";
        sql = "SELECT DISTINCT Country FROM tbl_ports ORDER BY Region";
        ds = DBModule.ExecuteQuery(sql, GV.cn, GV.trans);

        if (ds != null && ds.Tables != null)
        {
            ArrayList source = new ArrayList();
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                source.Add(row["Country"].ToString());
            }
            var str = JsonConvert.SerializeObject(source);
            context.Response.Cache.SetExpires(DateTime.Now.AddSeconds(600));
            context.Response.Cache.SetCacheability(HttpCacheability.Public);
            context.Response.Write(str);
        }
        else
        {
            context.Response.Write(JsonConvert.SerializeObject("empty"));
        }
    }
    private void DoDeleteGPNotice(HttpContext context)
    {
        var _id = context.Request.Params["id"];
        long id = 0;
        var result = "ok";
        if (long.TryParse(_id, out id) && id > 0)
        {
            GoodPricesNotice obj = new GoodPricesNotice();
            obj.ID = id;
            obj.Load(GV.cn, GV.trans);
            //update trang thai            
            obj.Delete(GV.cn, GV.trans);
        }
        else
        {
            result = "notok";
        }

        JsonConvert.SerializeObject("ok");
        context.Response.Write(result);
    }

    private void GetListCustomer(HttpContext context)
    {
        string stVal = "";
        string sql = "SELECT ID,NAME FROM tbl_customerrelation where listtype=1 order by Name";
        DataTable dt = DBModule.ExecuteQuery(sql, GV.cn, GV.trans).Tables[0];
        if (dt.Rows.Count > 0)
        {
            //var availableTags = [
            //        { label: "Sao Paulo", value: "SP" },
            //        { label: "Sorocaba", value: "SO" },
            //        { label: "Paulinia", value: "PA" },
            //        { label: "São Roque", value: "SR" }
            //   ];
            stVal = "[";
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (i > 0 && i < dt.Rows.Count)
                    stVal += ",";
                stVal += "{ label:\"" + dt.Rows[i]["Name"].ToString() + "\",value:\"" + dt.Rows[i]["ID"].ToString() + "\"}";
            }
            stVal += "]";
        }
        context.Response.Cache.SetExpires(DateTime.Now.AddSeconds(0));
        context.Response.Cache.SetCacheability(HttpCacheability.Public);
        context.Response.Write(stVal);
    }

    private void GetListCarrier(HttpContext context)
    {
        string stVal = "";
        string sql = "SELECT ID,NAME FROM tbl_carrs order by Name";
        DataTable dt = DBModule.ExecuteQuery(sql, GV.cn, GV.trans).Tables[0];
        if (dt.Rows.Count > 0)
        {
            stVal = "[";
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (i > 0 && i < dt.Rows.Count)
                    stVal += ",";
                stVal += "{ label:\"" + dt.Rows[i]["Name"].ToString() + "\",value:\"" + dt.Rows[i]["ID"].ToString() + "\"}";
            }
            stVal += "]";
        }
        context.Response.Cache.SetExpires(DateTime.Now.AddSeconds(0));
        context.Response.Cache.SetCacheability(HttpCacheability.Public);
        context.Response.Write(stVal);
    }
    private void GetListUserName(HttpContext context)
    {
        DataSet ds = null;
        string sql = "";
        sql = "SELECT UserName FROM tbl_adminusers ORDER BY UserName";
        ds = DBModule.ExecuteQuery(sql, GV.cn, GV.trans);

        if (ds != null && ds.Tables != null)
        {
            ArrayList source = new ArrayList();
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                source.Add(row["UserName"].ToString());
            }
            var str = JsonConvert.SerializeObject(source);
            context.Response.Cache.SetExpires(DateTime.Now.AddSeconds(600));
            context.Response.Cache.SetCacheability(HttpCacheability.Public);
            context.Response.Write(str);
        }
        else
        {
            context.Response.Write(JsonConvert.SerializeObject("empty"));
        }
    }
    private void GetListServiceArea(HttpContext context)
    {
        DataSet ds = null;
        string sql = "";
        //sql = "select distinct region from tbl_ports";
        sql = "select distinct name from tbl_serviceareas";
        ds = DBModule.ExecuteQuery(sql, GV.cn, GV.trans);

        if (ds != null && ds.Tables != null)
        {
            ArrayList source = new ArrayList();
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                source.Add(row["name"].ToString());
            }
            var str = JsonConvert.SerializeObject(source);
            context.Response.Cache.SetExpires(DateTime.Now.AddSeconds(600));
            context.Response.Cache.SetCacheability(HttpCacheability.Public);
            context.Response.Write(str);
        }
        else
        {
            context.Response.Write(JsonConvert.SerializeObject("empty"));
        }
    }
    private void GetListServiceAreaCode(HttpContext context)
    {
        DataSet ds = null;
        string sql = "";
        //sql = "select distinct region from tbl_ports";
        sql = "select distinct Code from tbl_serviceareas";
        ds = DBModule.ExecuteQuery(sql, GV.cn, GV.trans);

        if (ds != null && ds.Tables != null)
        {
            ArrayList source = new ArrayList();
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                source.Add(row["Code"].ToString());
            }
            var str = JsonConvert.SerializeObject(source);
            context.Response.Cache.SetExpires(DateTime.Now.AddSeconds(600));
            context.Response.Cache.SetCacheability(HttpCacheability.Public);
            context.Response.Write(str);
        }
        else
        {
            context.Response.Write(JsonConvert.SerializeObject("empty"));
        }
    }
}